package com.fanghuaiming.test.c4.阻塞;

import static com.fanghuaiming.netty.utils.ByteBufferUtil.debugAll;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

/****
 * @description:
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2021/9/21 下午4:38
 *
 */
@Slf4j
public class Server {

  public static void main(String[] args) throws IOException {
      //使用nio来理解阻塞模式，单线程
      ByteBuffer buffer = ByteBuffer.allocate(16);
      //1.创建服务器
      ServerSocketChannel ssc = ServerSocketChannel.open();

      //2.绑定监听端口
      ssc.bind(new InetSocketAddress(8080));

      List<SocketChannel> channels = new ArrayList<>();
      while (true){
          //3.accept简历与客户端的连接，SocketChannel用于与客户端进行通信
          log.info("connecting...");
          SocketChannel sc = ssc.accept();
          log.info("connected...{}",sc);
          channels.add(sc);
          //4.接收客户端发送的数据
          for (SocketChannel channel : channels){
              log.info("before read...{}",channel);
              channel.read(buffer);
              buffer.flip();
              debugAll(buffer);
              buffer.clear();
              log.info("after read...{}",channel);
          }
      }
  }
}
